
package hasthi.metamodel.resource;


import hasthi.common.HasthiException;
import hasthi.common.InvaliedResourceDataException;
import hasthi.manager.ManagedResourceType;
import hasthi.metamodel.ResourceUtils;

import java.util.Map;

import javax.xml.namespace.QName;
/**
 * MetaModel of a ManagedResource which resides in a remote Manager. The collected values are chached for 
 * limited time and they are fetched after them become stale
 * @author Srinath Perera(hperera@cs.indiana.edu)
 */

public class ManagedRemoteResourceImpl extends AbstractManagedResource implements EditableManagedResource{
    
    ManagedRemoteResourceImpl(ResourceModelContext modelContext,
            ManagedResourceType resource) throws InvaliedResourceDataException{
        super(modelContext,resource);
    }
    
    ManagedRemoteResourceImpl(QName name, ResourceModelContext modelContext, 
            String managerAgentURL, String category, String userDefinedType) throws InvaliedResourceDataException {
        super(name, modelContext, managerAgentURL, category, userDefinedType);
    }

    
    ManagedRemoteResourceImpl(ResourceModelContext modelContext, Map<QName, Object> extractedProperties,
            String managerAgentURL) throws InvaliedResourceDataException{
        super(modelContext, extractedProperties,managerAgentURL);
    }
    
    
    public String getProperty(String name) throws HasthiException {
        String value = null;
        //For given period of time, we shall cache the properties
        if((System.currentTimeMillis() - lastUpdated)/1000 < modelContext.getCacheForSeconds()){
            value = properties.get(name);
        }
        if(value != null){
            return value;
        }else{
            String holderURL = ResourceUtils.fetchHolderURL(modelContext,this.name);
            Map<QName,Object> rawParameterSet = ResourceUtils.fetchRemoteResourceParameters(modelContext,holderURL,this.name);
            for(QName propertyName:rawParameterSet.keySet()){
                //We format the object value as a String
                String strValue = modelContext.getConverter().convert(rawParameterSet.get(propertyName));
                this.properties.put(propertyName.getLocalPart(), strValue);
            }
            lastUpdated = System.currentTimeMillis();
            return properties.get(name);
        }
    }
}

